<template>
  <div
      class="task-item"
      :class="{
      completed: task.completed,
      active: isActive
    }"
      @click.stop="handleTaskClick"
  >
    <el-checkbox
        :model-value="task.completed"
        @update:model-value="handleCheckboxChange"
        class="task-checkbox"
    />

    <!-- 其余内容保持不变 -->
    <div class="task-content">
      <div
          ref="titleRef"
          class="task-title"
          :contenteditable="task.editingTitle && !task.completed"
          @click.stop="$emit('start-editing', { type: 'title', event: $event })"
          @blur="$emit('save-editing', { type: 'title', event: $event })"
          @keydown.enter.prevent="$emit('title-enter')"
          @keydown.down.prevent="$emit('navigate-to-desc')"
          spellcheck="false"
          :style="{
          transition: task.editingTitle ? 'all 0.2s ease' : 'color 0.3s ease'
        }"
      >{{ task.title }}</div>

      <div
          ref="descRef"
          class="task-description"
          :contenteditable="task.editingDesc && !task.completed"
          @click.stop="$emit('start-editing', { type: 'desc', event: $event })"
          @blur="$emit('save-editing', { type: 'desc', event: $event })"
          @keydown.enter.prevent
          @keydown.up.prevent="$emit('navigate-to-title')"
          spellcheck="false"
          :style="{
          transition: task.editingDesc ? 'all 0.2s ease' : 'color 0.3s ease, opacity 0.3s ease'
        }"
      >{{ task.description }}</div>

      <div class="task-date-container">
        <div
            v-if="task.date && task.showDateAsText"
            class="selected-date"
            @click="toggleDateMode"
        >
          <el-icon class="date-icon"><Calendar /></el-icon>
          <span>{{ formatDate(task.date) }}</span>
          <el-icon class="edit-icon"><Edit /></el-icon>
        </div>

        <div
            v-else
            class="task-date-buttons"
        >
          <el-button
              class="date-btn"
              :class="{ active: task.date === 'today' }"
              @click.stop="handleDateSelect('today')"
          >今天</el-button>
          <el-button
              class="date-btn"
              :class="{ active: task.date === 'tomorrow' }"
              @click.stop="handleDateSelect('tomorrow')"
          >明天</el-button>
          <el-button
              class="date-btn"
              @click.stop="openCalendar($event)"
              ref="calendarTrigger"
          >
            <el-icon><Calendar /></el-icon>
          </el-button>
        </div>
      </div>

      <div
          v-if="showCalendar"
          class="task-options-menu date-picker-container"
          @click.stop
          :style="{ left: calendarLeft + 'px', top: calendarTop + 'px' }"
      >
        <DatePicker
            :visible="showCalendar"
            :initial-date="getInitialDate()"
            @select="handleCalendarSelect"
            @close="handleCalendarClose"
        />
      </div>

      <el-button
          class="task-option"
          @click.stop="$emit('toggle-options', $event)"
          :icon="More"
      />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { More, Calendar, Edit } from '@element-plus/icons-vue'
import { ref, computed, nextTick, watch, onUnmounted, onMounted } from 'vue'
import DatePicker from '../Calendar/DatePicker.vue'
import type { Task } from '@/types/taskList'

const isActive = ref(false)
const titleRef = ref<HTMLElement | null>(null)
const descRef = ref<HTMLElement | null>(null)
const calendarTrigger = ref<HTMLElement | null>(null)

const calendarLeft = ref(0)
const calendarTop = ref(0)
const showDateButtons = computed({
  get() {
    if (!props.task.date) return true
    return !props.task.showDateAsText
  },
  set(value) {
    emit('update-show-date-mode', {
      taskIndex: props.taskIndex,
      showAsText: !value
    })
  }
})
const showCalendar = ref(false)

const props = defineProps<{
  activeCalendarTaskId: string | null
  task: Task
  taskIndex: number
  listIndex: number
}>()

const emit = defineEmits<{
  (e: 'task-complete', checked: boolean): void
  (e: 'start-editing', payload: { type: 'title' | 'desc'; event: Event }): void
  (e: 'save-editing', payload: { type: 'title' | 'desc'; event: Event }): void
  (e: 'title-enter'): void
  (e: 'navigate-to-desc'): void
  (e: 'navigate-to-title'): void
  (e: 'set-date', date: 'today' | 'tomorrow' | string): void
  (e: 'toggle-options', event: MouseEvent): void
  (e: 'set-active-calendar', taskId: string | null): void
  (e: 'update-show-date-mode', payload: { taskIndex: number; showAsText: boolean }): void
}>()

const formatDate = (date: string) => {
  if (date === 'today') return '今天'
  if (date === 'tomorrow') return '明天'

  const dateObj = new Date(date)
  if (isNaN(dateObj.getTime())) {
    return '选择日期'
  }

  const currentYear = new Date().getFullYear()
  const targetYear = dateObj.getFullYear()

  return targetYear === currentYear
      ? `${dateObj.getMonth() + 1}月${dateObj.getDate()}日`
      : `${targetYear}年${dateObj.getMonth() + 1}月${dateObj.getDate()}日`
}

const openCalendar = (event: MouseEvent) => {
  event.stopPropagation()
  if (props.task.completed) return
  emit('set-active-calendar', props.task.id)
  const triggerRect = (event.target as HTMLElement).getBoundingClientRect()
  calendarLeft.value = triggerRect.left + window.scrollX
  calendarTop.value = triggerRect.bottom + window.scrollY
  showCalendar.value = true
}

const handleCalendarClose = () => {
  showCalendar.value = false
  emit('set-active-calendar', null)
}

// 核心修改：通过emit触发store更新，不再单独操作localStorage
const handleCheckboxChange = (checked: boolean) => {
  // 直接触发父组件事件，通过store更新并存储（不要直接修改props）
  emit('task-complete', checked);
};

const getInitialDate = () => {
  if (props.task.date === 'today') return new Date()
  if (props.task.date === 'tomorrow') {
    const tomorrow = new Date()
    tomorrow.setDate(tomorrow.getDate() + 1)
    return tomorrow
  }
  const dateObj = new Date(props.task.date)
  return !isNaN(dateObj.getTime()) ? dateObj : new Date()
}

const toggleDateMode = () => {
  if (props.task.completed) return
  emit('update-show-date-mode', {
    taskIndex: props.taskIndex,
    showAsText: !props.task.showDateAsText
  })
}

const handleDateSelect = (date: 'today' | 'tomorrow') => {
  if (props.task.completed) return
  emit('set-date', date)
  emit('update-show-date-mode', {
    taskIndex: props.taskIndex,
    showAsText: true
  })
}

const handleCalendarSelect = (date: Date) => {
  if (props.task.completed) return
  const localDateStr = date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).replace(/\//g, '-')

  emit('set-date', localDateStr)
  emit('update-show-date-mode', {
    taskIndex: props.taskIndex,
    showAsText: true
  })
  handleCalendarClose()
}

const handleTaskClick = () => {
  isActive.value = true
  const clearActive = (e: MouseEvent) => {
    if (!e.target || !(e.target as HTMLElement).closest('.task-item')) {
      isActive.value = false
      document.removeEventListener('click', clearActive)
    }
  }
  setTimeout(() => {
    document.addEventListener('click', clearActive)
  }, 0)
}

watch(
    () => showDateButtons.value,
    (isShowing) => {
      if (isShowing) showCalendar.value = false
    }
)

const focusElement = (element: HTMLElement | null) => {
  if (element) {
    nextTick(() => {
      element.focus()
    })
  }
}

watch(
    () => [props.task.editingTitle, props.task.editingDesc],
    ([editingTitle, editingDesc]) => {
      if (editingTitle) focusElement(titleRef.value)
      if (editingDesc) focusElement(descRef.value)
    }
)

watch(showCalendar, (isShow) => {
  if (isShow) {
    const handleClickOutside = (e: MouseEvent) => {
      const target = e.target as Element | null
      const datePickerEl = document.querySelector('.date-picker')
      if (
          calendarTrigger.value?.contains(target) ||
          datePickerEl?.contains(target)
      ) {
        return
      }
      handleCalendarClose()
      document.removeEventListener('click', handleClickOutside)
    }
    nextTick(() => {
      document.addEventListener('click', handleClickOutside)
    })
  }
})

watch(
    () => props.activeCalendarTaskId,
    (newId) => {
      if (showCalendar.value && newId !== props.task.id) {
        showCalendar.value = false
      }
    }
)

onUnmounted(() => {
  if (props.activeCalendarTaskId === props.task.id) {
    emit('set-active-calendar', null)
  }
})

// 移除原有的localStorage读取逻辑，状态由store管理
onMounted(() => {});
</script>

<style scoped>
/* 样式保持不变 */
.task-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 14px 16px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: visible !important;
  margin-bottom: 10px;
}

.task-item.completed {
  padding: 8px 16px;
  background: #f0f0f0;
  border-color: #e0e0e0;
  min-height: 40px;
}

.task-item:not(.completed) {
  min-height: 60px;
}

.task-item:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border-color: #eee;
  z-index: 10;
}

.task-item.active {
  border-color: #1976d2;
  box-shadow: 0 0 0 2px rgba(25, 118, 210, 0.2);
  background-color: #f0f7ff;
}

.task-checkbox {
  margin-top: 3px;
  flex-shrink: 0;
  transition: transform 0.2s ease;
}

.task-checkbox:hover {
  transform: scale(1.05);
}

.task-content {
  flex: 1;
  overflow: visible !important;
}

.task-title {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 4px;
  outline: none;
  min-height: 24px;
  line-height: 1.5;
  color: #000;
  letter-spacing: 0.02em;
}

.task-item.completed .task-title {
  text-decoration: line-through;
  color: #999;
  margin-bottom: 0;
}

.task-title[contenteditable='true'] {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 4px;
  padding: 2px 4px;
  box-shadow: inset 0 0 0 1px #ddd;
}

.task-title[contenteditable='true']:focus {
  background-color: white;
  box-shadow: inset 0 0 0 1px #1976d2;
}

.task-description {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  outline: none;
  min-height: 20px;
  line-height: 1.6;
  letter-spacing: 0.03em;
}

.task-description[contenteditable='true'] {
  background-color: rgba(255, 255, 255, 0.6);
  border-radius: 4px;
  padding: 3px 4px;
  box-shadow: inset 0 0 0 1px #ddd;
}

.task-description[contenteditable='true']:focus {
  background-color: white;
  box-shadow: inset 0 0 0 1px #1976d2;
}

.task-date-container {
  position: relative;
  margin-top: 8px;
}

.selected-date {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #666;
  padding: 2px 8px;
  border-radius: 4px;
  cursor: pointer;
  width: fit-content;
  transition: background-color 0.2s ease;
}

.selected-date:hover {
  background-color: #f5f5f5;
}

.selected-date .date-icon {
  font-size: 12px;
  color: #1976d2;
}

.selected-date .edit-icon {
  font-size: 11px;
  color: #999;
  margin-left: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.selected-date:hover .edit-icon {
  opacity: 1;
}

.task-date-buttons {
  display: flex;
  gap: 6px;
  align-items: center;
  flex-wrap: wrap;
  position: relative;
  z-index: 1;
}

.date-btn {
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid #ddd;
  background: white;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
  transition: all 0.2s ease;
  position: relative;
}

.date-btn:hover {
  border-color: #1976d2;
  color: #1976d2;
  box-shadow: none;
}

.date-btn.active {
  background: #1976d2;
  color: white;
  border-color: #1976d2;
}

.date-btn .el-icon {
  font-size: 12px;
}

.task-option {
  border: none;
  background: none;
  color: #999;
  padding: 2px;
  margin-left: auto;
  cursor: pointer;
  flex-shrink: 0;
  transition: all 0.2s ease;
}

.task-option:hover {
  color: #333;
  transform: rotate(90deg);
}

.task-item.completed .task-description,
.task-item.completed .task-date-container,
.task-item.completed .task-option {
  max-height: 0;
  opacity: 0;
  transform: translateY(-10px);
  overflow: hidden;
  margin: 0;
  padding: 0;
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
}

.task-item:not(.completed) .task-description,
.task-item:not(.completed) .task-date-container,
.task-item:not(.completed) .task-option {
  transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
  max-height: 200px;
  opacity: 1;
  transform: translateY(0);
  overflow: visible;
}

.task-item.completed .task-title[contenteditable='true'] {
  pointer-events: none;
  background: transparent;
  box-shadow: none;
}
</style>